package com.dts.server.service;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dts.server.common.base.BaseAuthService;
import com.dts.server.common.base.BaseSession;
import com.dts.server.common.enums.ResultCode;
import com.dts.server.common.exception.CustomException;
import com.dts.server.common.result.ListResult;
import com.dts.server.common.util.PagerUtil;
import com.dts.server.db.dao.ProjectMonitorMapper;
import com.dts.server.dbutil.entity.ProjectMonitor;
import com.dts.server.query.ProjectMonitorQuery;

/**
 * @ClassName:  ProjectMonitorService
 * @author 范旭蛟
 * @date 2021年10月17日 下午4:17:29
 * @Description: 项目监控service
 */
@Service
@Transactional
public class ProjectMonitorService extends BaseAuthService {

	@Resource
	private ProjectMonitorMapper monitorMapper;
	
	/**
	 * 分页查询监控列表
	 * @param param
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public ListResult<ProjectMonitor> query(ProjectMonitorQuery param, BaseSession session) throws Exception {
		if(!vaildProjectAuth(param.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		Integer totalCount = monitorMapper.queryCount(param);
		if (totalCount <= 0) {
			throw new CustomException(ResultCode.S_NULL_ERROR);
		}
		param.setStart(PagerUtil.MathStart(param.getPagenum(), totalCount));
		List<ProjectMonitor> list = monitorMapper.query(param);
		return new ListResult<ProjectMonitor>(totalCount, list);
	}
	
	/**
	 * 
	 * @param templateId
	 * @return
	 * @throws Exception
	 */
	public List<ProjectMonitor> queryByTemplate(Integer templateId) throws Exception{
		return monitorMapper.queryByTemplate(templateId);
	}
	
	/**
	 * 新增监控
	 * @param monitor
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean add(ProjectMonitor monitor, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(monitor.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		monitor.setFlag(UUID.randomUUID().toString().replace("-", ""));
		return monitorMapper.add(monitor) > 0;
	}
	
	/**
	 * 编辑
	 * @param monitor
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean edit(ProjectMonitor monitor, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(monitor.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		return monitorMapper.edit(monitor) > 0;
	}
	
	/**
	 * 删除
	 * @param monitor
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean delete(ProjectMonitor monitor, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(monitor.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		return monitorMapper.delete(monitor) > 0;
	}
}
